﻿export function init(entityTreeId, dotNetHelper) {
    dispose(entityTreeId);
    window.SORTABLE_INSTANCES ??= {};
    window.SORTABLE_INSTANCES[entityTreeId] ??= [];
    setTimeout(() => {
        const itemsContainerEls = document.querySelectorAll('.dxbl-treeview-items-container[data-items-container]')
        for (const itemsContainerEl of itemsContainerEls) {
            window.SORTABLE_INSTANCES[entityTreeId].push(new Sortable(itemsContainerEl, {
                sort: false,
                draggable: '.entity-property-node',
                group: {
                    name: 'detail-view-editor',
                    pull: 'clone',
                    put: false,
                },
                setData: function (dataTransfer, dragEl) {
                    const propertyPath = dragEl.classList.values().toArray().findLast(e => e.startsWith('p-path-'))?.slice(7).replace(/-/g, '.');
                    if (propertyPath) {
                        dataTransfer.setData('Text', `<p>${propertyPath}</p>`);
                    }
                }
            }));
        }
    }, 1000);
}

export function dispose(entityTreeId) {
    if (window.SORTABLE_INSTANCES && window.SORTABLE_INSTANCES[entityTreeId]) {
        for (const sortable of window.SORTABLE_INSTANCES[entityTreeId]) {
            sortable.destroy();
        }
        delete window.SORTABLE_INSTANCES[entityTreeId];
    }
}